//
//  YCOAuthViewController.swift
//  WeiboDemo
//
//  Created by 尹成 on 2017/1/12.
//  Copyright © 2017年 yc. All rights reserved.
//

import UIKit
import SVProgressHUD

class YCOAuthViewController: UIViewController{
    
    private lazy var webview = UIWebView()
    override func loadView() {
        view = webview
        
        webview.scrollView.isScrollEnabled = false

        view.backgroundColor = UIColor.lightGray
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭",
                                                           target: self,
                                                           action: #selector(closeView))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充",
                                                           target: self,
                                                           action: #selector(inputUserInfoAction))
        webview.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirectURL)"
        guard let url = URL(string:urlString) else {
            return
        }
        
        let request = URLRequest(url: url)
        webview.loadRequest(request)
        
    }
    
    @objc fileprivate func closeView() {

        SVProgressHUD.dismiss()
        
      //  navigationController?.dismiss(animated: true, completion: nil)
        
        //👆 👇 效果相同
        
        dismiss(animated: true, completion: nil)
    }
    
    
    /// webView的注入 ： 使用 js 自动填充网页所需帐号
    @objc private func inputUserInfoAction(){
        let js = "document.getElementById('userId').value = 'wyyincheng@163.com';" + "document.getElementById('passwd').value = '123abc123';"
            
        webview.stringByEvaluatingJavaScript(from: js)
    }
    
}

extension YCOAuthViewController:UIWebViewDelegate{
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(WeiboRedirectURL) == false {
            return true
        }
        
        /// query 就是url中 ‘？’ 后面所有部分
        let query = request.url?.query
        if query?.hasPrefix("code=") == false {
            // FIXME: 将取消 跟 错误一样对待了， 应该区分对待，取消直接dismiss，错误需要提示并留在原页面
            self.closeView()
            return false
        }
        
        // 获取 token
        let code = query?.substring(from: "code=".endIndex) ?? ""
        
        YCNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            self.closeView()
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
